<?php
/**
  * Musashi - A project manager for music groups and bands
  * Copyright (C) 2010 Daniel Torres
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  */

/**
 *  Contains the Venue display component
 *  This should not be triggered independently, but as a component of another page.
 */


/**
 *  Display the venue information page
 *  @param $a_allowEdit If true, we display an edit version of the component
 *  @param $showID      ID of the show to display
 *  @param $model       The show model
 *  @param $showData    data pertaining this show
 */
function displayVenue( $a_alowEdit = false, $showID, &$model, &$showData )
{
    $venueData     = $model->getVenueList();            
    $venueFromList = true;
    $showVenue     = $showData['venue'];
        
    // Don't select from our list if we have no venues
    if( count($venueData) == 0 )
    {
        $venueFromList = false;
    }
    ?>
    <script language="javascript" type="text/javascript">
    <!--
        // current venue
        var currentVenue = <?php echo $showData['venue']; ?>;

        // An array with all of our venue data. This makes the page more expensive, but
        // saves in terms of performance
        var venueData = [];
        <?php
        foreach( $venueData as $venue )
        {
            // id, name, description, address, contact, notes, link
            $newEntry = sprintf( 'venueData.push([%d,"%s","%s","%s","%s","%s","%s"]);',
                $venue['id'], $venue['name'], $venue['description'], $venue['address'], $venue['contact'], str_replace("\n","<cr>",str_replace("\r","<lf>",$venue['notes'])), $venue['link'] );
            echo $newEntry;        
        }
        ?>
        
        // Returns a venue by a given search field, or null if not found
        function getVenueByElement( value, elementIndex )
        {
            for( i = 0; i < venueData.length; i++ )
            {
                if ( venueData[i][elementIndex] == value ){
                    return venueData[i];
                }
            }
            
            return null;
        }
        
        // Validates the venue
        function validateVenueForm()
        {
            var theForm = document.venueForm;
            
            // Name and address are required
            if ( theForm.name )
            {
                if ( theForm.name.value == "" )
                {
                    alert("Please indicate a name for this venue");
                    return false;                    
                }
                
                if (theForm.name.value.search(/'/i) != -1 )
                {
                    alert("The venue name contains an invalid character [']. Please try again");
                   return false;
                }
            }
            
            if ((theForm.address) && (theForm.address.value == ""))
            {
                alert("Please indicate an address for this venue");
                return false;
            }
            
            // Test
            if ( getVenueByElement(theForm.name.value,1) != null )
            {
                alert("A venue with the same name exists already. Please choose something different");
                return false;
            }
            
            return true;
        }
        
        // Shows the provided venue data in the venue display panel
        function showVenueInfo( venueInfo )
        {
            if( venueInfo != null )
            {
                _jq('#vu-name').html(venueInfo[1]);
                _jq('#vu-desc').html(venueInfo[2]);
                _jq('#vu-addr').html(venueInfo[3]);
                _jq('#vu-cntc').html(venueInfo[4]);
                
                // Make sure all <br> are correct carriage returns
                _jq('#vu-notes').html(venueInfo[5].replace(new RegExp('<cr>','g'),'\n').replace(new RegExp('<lf>','g'),'\r'));
                
                if( venueInfo[6] == "" ) {
                    _jq('#vu-lnka').hide();
                } else {
                    _jq('#vu-lnka').show();
                    _jq('#vu-lnka').attr('href',venueInfo[6]);
                }
                
                // This one is important: Update this venue's form id
                _jq('#vu-id').val(venueInfo[0]);
                
                _jq('#venueUpdate').fadeIn(GUI_FADE_SPEED);
            }            
            
        }
            
        // Change the venue to an alternate one, provided by our combo box
        _jq(function(){
            _jq('#cb-venueSelector').change(function(){            
                var newVenue = _jq('#cb-venueSelector').val();
                
                // Do nothing if this is the 'zero' option or the previously selected one
                if ( (newVenue == 0) || (newVenue == currentVenue) )
                {
                    _jq('#cb-venueSelector').val(currentVenue);
                    return;
                }
                
                // A valid venue. Change the displayed information 
                var venueInfo = getVenueByElement( newVenue, 0 );
                showVenueInfo( venueInfo );
                
                // Update quietly            
                _jq.ajax({
                    type: "POST",
                    url: "<?php echo JRoute::_('index.php?');?>",
                    data: "<?php echo 'option=com_musashi&controller=shows&task=updateVenue&sid='.$showID; ?>" + "&vid=" + newVenue
                });
                
                currentVenue = newVenue;                        
                return false;
                
            });
        });
            
        // Submits new venue comments
        _jq( function() {
            _jq('form[name="venueDisplayForm"]').submit(function(){
                
                // Because the venue description is contained as text, elliminate carriage returns. JS
                // hates this
                var noteComponent = _jq('#vu-notes');
                var formData = _jq('form[name="venueDisplayForm"]').serialize();
                
                // Update all required information
                _jq.ajax({
                    type: "POST",
                    url: "<?php echo JRoute::_('index.php?');?>",
                    data: formData,
                    success: function(msg)
                    {
                        alert('venue comments updated');
                    }
                });
                
                // Update our current comment records. However, use correct carriage returns
                var venueInfo = getVenueByElement( currentVenue, 0 );
                if( venueInfo ) {
                    venueInfo[5] = noteComponent.val().replace( new RegExp('<br>','g'), '\\n');
                }
                
                return false;            
            });
        });
        
        // Shows the select venue by list form
        _jq(function(){
            _jq('#venue-selection-list').click(function(){
                // Hide the form
                _jq('#newVenue').hide();
                
                // Show the combo
                _jq('#selectVenueByList').show(GUI_FADE_SPEED);
                
                // If the current combo item is a valid selection, show it
                var cbVenue = _jq('#cb-venueSelector').val();
                if( cbVenue != 0 ) {
                    showVenueInfo( getVenueByElement( cbVenue, 0 ) );
                }
            });            
        });
        
        // Shows the new venue form
        _jq(function(){
            _jq('#venue-selection-new').click(function(){
                
                // Hide some
                _jq('#selectVenueByList').hide(GUI_FADE_SPEED);
                _jq('#venueUpdate').hide();
                
                // Display some
                _jq('#newVenue').fadeIn(GUI_FADE_SPEED);                
            });
            
        });
    
    -->
    </script>

    <a name="venue" style="text-decoration:none;">
    <section id='show-data'>
        <div id='section-title'>
            <h1>Venue</h1>
        </div>
        
        <!-- Venue selection type -------------------------------------- -->
        <form id="venue-input-selection">
            
            <!-- Select from a list ------------------------------------ -->
            <input type="radio" name="venue-selection" id="venue-selection-list" value="list" <?php
                if ($venueFromList){
                    echo "checked";
                } else {
                    echo "disabled";
                }
                ?> />Select from a list of existing venues<br/>                    
            <div id="selectVenueByList" <?php
                if(!$venueFromList){
                    echo "style='display:none'";
                } else {
                    echo "style='display:block'";
                } ?>  >
                <select name="venueSelector" id='cb-venueSelector' style="margin-left:2em;" >
                    <option value="0">---Select a venue----</option>
                    <?php
                    foreach( $venueData as $venue )
                    {
                        $vid = $venue['id'];
                        if($vid == $showVenue ){
                            echo '<option value="'.$vid.'" selected>'.$venue['name'].'</option>';
                        } else {
                            echo '<option value="'.$vid.'">'.$venue['name'].'</option>';
                        }
                    }
                    ?>
                </select><br/>
            </div>
            
            <!-- Create a new venue ------------------------------------ -->
            <input type="radio" name="venue-selection" id="venue-selection-new" value="new" <?php if(!$venueFromList){ echo "checked"; }  ?> />Create a new venue
        </form>
        
        <!-- New venue content ----------------------------------------- -->
        <div id="newVenue" <?php
                if($venueFromList){
                    echo "style='display:none'";
                } else {
                    echo "style='display:block'";
                } ?>  >
            <form id="form-basic-information" name='venueForm' method='post' onsubmit='return validateVenueForm();' action="<?php echo JRoute::_('index.php?');?>">
                <fieldset class="show-data-left" style="height:16em;">
                    <ol>
                        <li>
                            <label for="name">Venue name</label>
                            <input type="text" id="vf-name" name="name" maxlength="45" style="width:160px;" />
                        </li>
                        <li>
                            <label for="address">Address</label>
                            <input type="text" id="vf-address" name="address" maxlength="45" style="width:160px;" />
                        </li>
                        <li>
                            <label for="contact">Contact</label>
                            <input type="text" id="vf-contact" name="contact" style="width:160px;" />
                        </li>
                        <li>
                            <label for="link">Web link</label>
                            <input type="text" id="vf-link" name="link" maxlength="45" style="width:160px;" />
                        </li>
                    </ol>
                </fieldset>
                <fieldset class="show-data-right">
                    <label for="description" style="width:100%; text-align:left;">Description</label>
                    <textarea name="description" id="vf-description" style="width: 80%; height:50%;"></textarea>
                    <br/>
                    <label for="notes" style="width:100%; text-align:left;">Notes</label>
                    <textarea name="notes" id="vf-notes" style="width: 80%; height:50%;"></textarea>
                </fieldset>
                <fieldset class='show-data-save'>
                    <input type="submit" id="vf-submit" name="submit" value="Save venue"/>
                    and notify 
                    <select name='notify'>
                        <?php echo $model->getNotificationTargetsHTMLCombo(); ?>
                    </select>                    
                </fieldset>
                <input type="hidden" name="option"     value="com_musashi" />
                <input type="hidden" name="task"       value="addVenue" />
                <input type="hidden" name="controller" value="shows" />
                <input type="hidden" name="sid"        value="<?php echo $showID; ?>" />
            </form>
        </div>
        
        <!-- venue descriptor content ----------------------------------- -->            
        <?php
        if ($showData['venue'] != 0 )
        {
            $venueValues = $model->getVenueData( $showData['venue'] );
            $venueName   = $venueValues['name'];
            $venueDesc   = $venueValues['description'];
            $venueAddr   = $venueValues['address'];
            $venueContact= $venueValues['contact'];
            $venueLink   = $venueValues['link'];
            $venueNotes  = $venueValues['notes'];
            $venueDisp   = 'display:block;';
        }
        else
        {
            $venueName   = "";
            $venueDesc   = "";
            $venueAddr   = "";
            $venueContact= "";
            $venueLink   = "";
            $venueNotes  = "";
            $venueDisp   = "display:none;";
        }
        ?>
        <div id="venueUpdate" style="<?php echo $venueDisp; ?>">                
            <form id="form-basic-information" style='height:auto;' name='venueDisplayForm'>
                <fieldset class="show-data-left">
                    <h2 id='vu-name'><?php echo $venueName; ?></h2>
                    <h3 id='vu-desc'><?php echo $venueDesc; ?></h3>
                    <h4 id='vu-addr' style='margin:15px 0 0 0;'><?php echo $venueAddr; ?></h4>
                    <h4 id='vu-cntc' style='margin:5px 0 0 0';><b>Contact:</b> <?php echo $venueContact; ?></h4>
                    <h4 id='vu-link'><?php
                        if ($venueLink != "" )
                        {
                            echo '<a id="vu-lnka" href="'.$venueLink.'">[Link]</a>';
                        }
                        else
                        {
                            echo '<a id="vu-lnka" href="#" style="display:none">[Link]</a>';
                        }
                        ?>
                    </h4>                        
                </fieldset>
                <fieldset class="show-data-right" style="height:5em;">
                    <label for="notes" style="width:100%; text-align:left;">Notes</label>
                    <textarea name="notes" id="vu-notes" style="width: 80%; height:80%;"><?php echo $venueNotes; ?></textarea>                        
                </fieldset>
                <fieldset class='show-data-save' style='padding: 1.5em 0px 0px 33em;'>
                    <input type="submit" id="update" name="submit" value="Update notes"/>
                    and notify 
                    <select name='notify'>
                        <?php echo $model->getNotificationTargetsHTMLCombo(); ?>
                    </select>                    
                </fieldset>
                <input type="hidden" name="option"     value="com_musashi" />
                <input type="hidden" name="task"       value="updateVenueComments" />
                <input type="hidden" name="controller" value="shows" />
                <input type="hidden" name="vid"        value="<?php echo $venueValues['id']; ?>" id='vu-id' />
                <input type="hidden" name="sid"        value="<?php echo $showID; ?>" />
            </form>
        </div>
    </section>
    </a>
    <?php    
}
?>
